#ifndef CATEGORYCHILDMODEL_H
#define CATEGORYCHILDMODEL_H

#include <QAbstractItemModel>
#include <QVector>
#include <QStringList>
#include <QPersistentModelIndex>


class CategorizerModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    CategorizerModel(const QAbstractItemModel* categoryModel, const QAbstractItemModel* categorizableModel,
                     QObject *parent = 0);

    bool isCategory(const QModelIndex& index) const;

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    int rowCount (const QModelIndex &parent = QModelIndex()) const;

    Qt::ItemFlags flags(const QModelIndex &index) const;
    QModelIndex index(int row, int column,
                      const QModelIndex &parent = QModelIndex()) const;
    QModelIndex parent(const QModelIndex &index) const;

    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    
private slots:
    // Slots for the category model

    void category_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
    void category_rowsAboutToBeInserted(const QModelIndex &parent, int first, int last);
    /*void category_rowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart,
                              int sourceEnd, const QModelIndex &destinationParent,
                              int destinationRow);*/
    void category_rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last);
    void category_rowsInserted(const QModelIndex &parent, int first, int last);
    //void category_rowsMoved();
    void category_rowsRemoved();

    // Slots for categorizable model

    void item_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
    void item_rowsAboutToBeRemoved(const QModelIndex &parent, int first, int last);
    void item_rowsInserted(const QModelIndex &parent, int first, int last);

    // Common slots

    void common_modelAboutToBeReset();
    void common_modelReset();
    //void common_rowsMoved();

private:
    QList<QList<QPersistentModelIndex> > itemList;
    const QAbstractItemModel *_categoryModel;
    const QAbstractItemModel *_itemModel;

    void addItem(int row);
    void updateItem(int row);
    void removeItem(int row);

    void addCategory(int row, bool moveRows = true);
    void updateCategory(int row);
    void removeCategory(int row);

    void checkAndMoveUncategorizedItems();

    QString getCategoryForIndex(const QModelIndex& itemIndex) const;
    QModelIndex getCategoryParentForIndex(const QModelIndex& itemIndex) const;

    QModelIndex findRow(int row) const;

};

#endif // CATEGORYCHILDMODEL_H
